package com.jianqiao.delivery.exchange.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jianqiao.delivery.exchange.domain.vo.ExchangeVo;
import com.jianqiao.delivery.exchange.domain.vo.SelectCurrenciesParam;
import com.jianqiao.delivery.exchange.service.ExchangeService;
import com.jianqiao.delivery.util.HttpClientUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * author: cyx
 * create: 2024/10/18 11:27
 **/
@Service
public class ExchangeServiceImpl implements ExchangeService {

    @Value("${exchange.key}")
    private String exchangeKey;

    @Value("${exchange.url}")
    private String exchangeUrl;


    @Override
    public AjaxResult getExchange(SelectCurrenciesParam currenciesParam) throws JsonProcessingException {
        currenciesParam.setKey(exchangeKey);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(currenciesParam);
        Map paramMap = objectMapper.readValue(json, HashMap.class);
        Map map = HttpClientUtil.doGet(exchangeUrl, paramMap);

        String resultString = map.get("resultString").toString();
        HashMap resultMap = objectMapper.readValue(resultString, HashMap.class);

        String code = resultMap.get("code").toString();
        if (!"1".equals(code)) {
            return AjaxResult.error("出现未知错误，请稍后再试，或联系工作人员");
        }

        Object dataStr = resultMap.get("data");
        Map<? ,ExchangeVo> dataMap = (Map<?, ExchangeVo>) dataStr;

        return AjaxResult.success(dataMap);
    }
}
